<template>
  <ZForm
    :fields="registerFields"
    :initial-values="registerData"
    :schema="registerSchema"
    @submit="onSubmit"
  >
    <ZButton
      class="mt-2"
      color="primary"
      icon-class="icon-[mdi--how-to-reg-outline] size-6"
      type="submit"
      :loading="isFetching"
    >
      注 册
    </ZButton>
    <div class="flex justify-center items-center p-4">
      <span>已有账户?</span>
      <a
        class="mx-2 text-primary hover:text-secondary"
        href="#"
        @click="emit('change')"
      >
        登录
      </a>
    </div>
  </ZForm>
</template>
<script setup lang="ts">
import { z } from "zod";
import type { FormFields } from "@/components/form/types";
import ZForm from "@/components/form/ZForm.vue";
import ZButton from "@/components/ui/ZButton.vue";

import { useMutation } from "@pinia/colada";
import { register } from "@/apis/user";
import type { SubmissionContext } from "vee-validate";

const emit = defineEmits(["change"]);
const registerSchema = z
  .object({
    email: z.string().email("无效的邮箱"),
    password: z.string().min(6, "密码至少6位"),
    confirmPassword: z.string().min(6, "密码至少6位"),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "密码不一致",
    path: ["confirmPassword"],
  });

const registerFields: FormFields = [
  {
    name: "email",
    label: "邮箱",
    type: "email",
  },
  {
    name: "password",
    label: "密码",
    type: "password",
  },
  {
    name: "confirmPassword",
    label: "确认密码",
    type: "password",
  },
];

const registerData = {
  email: "",
  password: "",
  confirmPassword: "",
};

const { mutateAsync: registerMutate, isLoading: isFetching } = useMutation({
  mutation: register,
});

async function onSubmit(
  values: z.infer<typeof registerSchema>,
  { resetForm, setErrors }: SubmissionContext
) {
  try {
    const response = await registerMutate(values);
    if (response.success) {
      // 重置表单
      resetForm();
      emit("change");
    } else {
      // 设置错误信息
      if (response.errors) setErrors(response.errors);
    }
  } catch (error) {
    console.error("注册失败:", error);
    setErrors({
      api: "注册失败，请稍后再试。",
    });
  }
}
</script>
